package com.dgut.controller;

import com.dgut.bean.Declare;
import com.dgut.bean.FrontDeclare;
import com.dgut.bean.User;
import com.dgut.service.DeclareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/declare")
public class DeclareController {

    @Autowired
    private DeclareService declareService;

    @RequestMapping("/declareForm")
    public String declareForm() {
        return "declareForm";
    }

    @RequestMapping("/personTable")
    public String personTable() {
        return "personTable";
    }

    //添加申报
    @PostMapping("/addDeclare")
    public void addDeclare(@RequestBody FrontDeclare frontDeclare, HttpSession session) {
//        获取uid
        User user = (User) session.getAttribute("user");
        frontDeclare.setUid(user.getUid());
//        记录申报时间
        frontDeclare.setDeclareDate(new Date());
//        System.out.println(frontDeclare);
//        转化类型
        Declare declare = declareService.FrontD_TO_D(frontDeclare);
//        System.out.println(declare);
//        数据库填写数据
        declareService.addDeclare(declare);

    }

    //查看个人申报记录
    @RequestMapping("/personRecord")
    public @ResponseBody
    List<FrontDeclare> personRecord(HttpSession session) {
        //获取uid
        User user = (User) session.getAttribute("user");
//        查找
        List<Declare> declares = declareService.findByUid(user.getUid());
//        转化类型
        List<FrontDeclare> frontDeclares = new ArrayList<>();
        for (Declare declare : declares) {
            FrontDeclare frontDeclare = declareService.D_TO_FrontD(declare);
            frontDeclares.add(frontDeclare);
        }
        return frontDeclares;
    }

    //模糊查询，查询用户个人的申报记录
    @RequestMapping("/searchPersonJson")
    public @ResponseBody
    List<FrontDeclare> searchPersonJson(String keyword, HttpSession session) {
        //获取uid
        User user = (User) session.getAttribute("user");
        //查找
        List<Declare> declares = declareService.searchPerson(user.getUid(), keyword);
        //转化类型

        List<FrontDeclare> frontDeclares = new ArrayList<>();
        for (Declare declare : declares) {
//            System.out.println(declare);
            FrontDeclare frontDeclare = declareService.D_TO_FrontD(declare);
            frontDeclares.add(frontDeclare);
//            System.out.println(frontDeclare);
        }
        return frontDeclares;
    }
}
